Scroll to the top of the page using JavaScript/jQuery?
I've a on the page, when this button is pressed a hidden is shown using jQuery.
我有一個在頁面上,點擊後一個隱藏的div會透過jQuery顯示
How do I scroll to the top of the page using a JavaScript/jQuery command in that function? It is desirable even if the scroll bar instantly jumps to the top. I'm not looking for a smooth scrolling.
我該如何用JavaScript/jQuery達成點擊後立刻跳到頁面頂端?
1.純JS
If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript window.scrollTo method -- passing in 0,0 will scroll the page to the top left instantly.
如果你不在乎動畫效果,那你就不用用特殊的插件,直接用window.scrollTo方法就可以了,
window.scrollTo(x-coord, y-coord);
Parameters
參數x-coord掌控平行的點、y-coord則是垂直的點
x-coord is the pixel along the horizontal axis.
y-coord is the pixel along the vertical axis.
2.jQuery
If you do want smooth scrolling, try something like this:
如果你想達到平滑的捲動可以試試看這樣:
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
That will take any tag whose href="#top" and make it smooth scroll to the top.